# -*- coding: utf-8 -*-
# @Time    : 2021/11/13 19:06
# @Author  : travel2040
# @Email   : travel2040@163.com
# @File    : 无限极分类递归函数.py


def getTree(data,pid,level=0):

    result = []

    for v in data:
        if v["pid"]==pid:
            v["level"] = level

            if "childs" not in v.keys():
                v["childs"]=[]

            inner_result = getTree(data,v["id"],level+1)

            if inner_result:
                for inner_v in inner_result:
                    v["childs"].append(inner_v)

            result.append(v)

    return result


if __name__ == '__main__':
    data = [
        {"id": 1, "name": "A", "pid": 0},
        {"id": 2, "name": "B", "pid": 0},
        {"id": 6, "name": "B-1", "pid": 2},

        {"id": 3, "name": "A-1", "pid": 1},
        {"id": 4, "name": "A-1-1", "pid": 3},

        {"id": 5, "name": "A-2", "pid": 1},

    ]

    result = getTree(data,0)
    for v in result:
        print(v)
